var resourcesSupportObj = {
	openAddEditFormResource : function(action) {
		new Effect.SlideDown('formAddEditResource', {direction: 'top', duration: .3});
		$('controlBar').style.display = 'none';
		$('formAction').value = 'add';
		$('resourceID').value = 0;
	}, 
	closeAddEditFormResource : function() {
		new Effect.SlideUp('formAddEditResource', {direction: 'top', duration: .3});
		resourcesSupportObj.clearAddEditFormResource();
		$('controlBar').style.display = '';
	},
	openAddEditForm : function(action) {
		new Effect.SlideDown('formAddEdit', {direction: 'top', duration: .3});
		$('buttonAdd').style.display = 'none';
		this.getFileCategories('Resource File');		
	},
	closeAddEditForm : function() {
		new Effect.SlideUp('formAddEdit', {direction: 'top', duration: .3});
		this.clearAddEditForm();
		$('progressDiv').innerHTML = '';
		$('progressDiv').style.display = 'none';
		$('buttonAdd').style.display = '';
	},
	newCategoryForm : function(catType) {
		var fileFrame = frames['fileFrame'];
		
		if (catType == 'main') {
			var catField = 'fileCat';
			var catLink = 'newCatLinkMain';
			var newCatField = 'newCatFieldMain';
		} else if (catType == 'sub') {
			var catField = 'fileSubCat';
			var catLink = 'newCatLinkSub';
			var newCatField = 'newCatFieldSub';
		}
		
		if (fileFrame.$(newCatField).style.display == 'none') {
			fileFrame.$(newCatField).style.display = '';
			fileFrame.$(catField).style.display     = 'none';
			fileFrame.$(catLink).innerHTML      = 'Cancel';
			fileFrame.$(newCatField).focus();
		} else {
			fileFrame.$(newCatField).style.display = 'none';
			fileFrame.$(catField).style.display     = '';
			fileFrame.$(catLink).innerHTML      = 'New Category';
		}
	},
	clearAddEditForm : function() {
		var fileFrame = frames['fileFrame'];
		fileFrame.$('ptiSharedResource').checked = false;
		fileFrame.$('newCatFieldMain').value = '';
		fileFrame.$('newCatFieldSub').value = '';
		fileFrame.$('fileTitle').value = '';
		var editorInstance = fileFrame.$('fileDesc');
		fileFrame.$('fileDesc').value = '';	
	},
	clearAddEditFormResource : function() {
		$('formAction').value     = 'add';
		$('resourceID').value     = '';
		$('rType').value          = '';
		$('rName').value          = '';
		$('rDescription').value   = '';
		$('rURL').value           = '';
		$('resourceID').value     = '';
		$('rContactPerson').value = '';
		$('rServiceArea').value   = '';
		$('rAddress').value       = '';
		$('rCity').value          = '';
		$('rZip').value           = '';
		$('rPhone').value         = '';
		$('rFax').value           = '';
		$('rEmail').value         = '';
		$('rNotes').value         = '';
		$('rCountyList').innerHTML= '';		
	},
	addExtDateField : function() {
		var dateFieldTraining = 'trainingDate';		
		
		// Convert dateBirth field to Ext DateField		
		var dateFieldTraining = new Ext.form.DateField({
			width: 83,
		    allowBlank: true,
		    format: 'm/d/Y',
			applyTo: dateFieldTraining
		});				
	},
	getSharedResourceCats : function() {
		var fileFrame = frames['fileFrame'];
		if (fileFrame.$('ptiSharedResource').checked == true) {
			this.getFileCategories('Shared Resource File','json','main',0);
		} else {
			this.getFileCategories('Resource File','json','main',0);
		}
	},
	getFileCategories : function(siteArea,render,catType,catID) {
		var params = 'handler=getCategories&siteArea='+siteArea+'&renderType='+render+'&catType='+catType+'&catID='+catID;
		var ajaxResults = new Ajax.Request('ajaxDirector.php', {
			method: 'POST',
			parameters: params,
			onSuccess: function(transport) {
				if (transport.responseText != 0) {
					resourcesSupportObj.populateCategorySelect(transport.responseText);
				}	
			},
			onFailure: function() {
				alert('Oops!');
			}	
		});
	},
	populateCategorySelect : function(stringJSON) {
		var fileFrame = frames['fileFrame'];
		var jsonObject = stringJSON.evalJSON();
		var totalItems = (jsonObject.Categories.length)-1;
		var catType    = jsonObject.CatType;
				
		if (catType == 'sub') {
			fileFrame.$('subCatContainer').style.display = '';
			var catSelect = 'fileSubCat';
			var selectedCat = fileFrame.$('tempSubCat').value;
		} else {
			fileFrame.$('subCatContainer').style.display = 'none';
			var catSelect = 'fileCat';
			var selectedCat = fileFrame.$('tempMainCat').value;
		}
		
		/*
		 * Clear the appropriate select menu
		 */
		fileFrame.$(catSelect).options.length = 0;	
		
		for(var a=0;a<=totalItems;a++) {
			var catTitle = jsonObject.Categories[a].CatTitle;
			var catID    = jsonObject.Categories[a].CatID;
			fileFrame.$(catSelect).options[a] = new Option(catTitle,catID);	
			if (selectedCat == catID) {
				fileFrame.$(catSelect).selectedIndex = a;
			}
		}
	},
	copyCounties : function(county) {
		var countyList = $('rCountyList').innerHTML;
		countyList += '<p id="county_'+county+'" style="cursor: pointer;" class="countyList iconRemoveText" onClick="resourcesSupportObj.removeCounties(\''+county+'\');" title="Remove county">'+county+'</p>';
		$('rCountyList').innerHTML = countyList;
	},
	removeCounties : function(county) {
		$('county_'+county).remove();	
	}
}

var resourcesGetObj = {
	getResources : function(resourceGroupID) {
		var params = 'handler=getResources&resourceGroupID='+resourceGroupID+'&renderType=json';
		Ext.Ajax.request({
	        url:    'ajaxDirector.php',
	        method: 'POST',
	        params: params,
	        success: function(response) {
	        	resourcesGetObj.renderResourcesToGrid(response.responseText);
	        },
	        failure: function(response) {
	        	logErrorAJAX(response);
	        }
	    });			
	},
	getFileCategories : function(siteArea,mainID) {
		var params = 'handler=getFileCategories&siteArea='+siteArea+'&mainID='+mainID;
		var ajaxResults = new Ajax.Request('ajaxDirector.php', {
			method: 'POST',
			parameters: params,
			onSuccess: function(transport) {
				if ( (mainID>0) && (transport.responseText == '0') ) {
					/*
					 * We have no sub-categories, go get files instead
					 */
					resourcesGetObj.getResourceFiles(mainID);
				} else {
					resourcesGetObj.renderFileCategories(transport.responseText);
				}	
			},
			onFailure: function() {
				alert('Oops!');
			}	
		});
	},
	renderResourcesToGrid : function(stringJSON) {
		var jsonObject = stringJSON.evalJSON();
		
		var totalItems    = jsonObject.Resources.length
		var returnedRows  = ((jsonObject.Resources.length)-1);
							
		if (totalItems>0) {			
			/*
			 * Create table header
			 */			
			var stringOut = '<table class="dataTable" style="font-size: 1em;">';
			stringOut    += '<tr>';
			stringOut    += '<th style="width: 5%;"></th>';
			stringOut    +=	'<th onmouseover="this.className=\'thHover\';" onmouseout="this.className=\'\';" style="width: 35%;">Provider Name</th>' + 
							'<th onmouseover="this.className=\'thHover\';" onmouseout="this.className=\'\';" style="width: 35%;">Provider Contact</th>' +
							'<th onmouseover="this.className=\'thHover\';" onmouseout="this.className=\'\';" style="width: 10%;">Counties Served</th>' +
							'<th onmouseover="this.className=\'thHover\';" onmouseout="this.className=\'\';" style="width: 10%;">Date Entered</th>';
			stringOut    += '</tr>';	
			
			for(a=0;a<=returnedRows;a++) {
				var rID           = jsonObject.Resources[a].ProviderID;
				var rName         = jsonObject.Resources[a].ProviderName;
				var rURL          = jsonObject.Resources[a].ProviderWebURL;
				var rEmail        = jsonObject.Resources[a].ProviderEmail;
				var rDateEntered  = jsonObject.Resources[a].DateEntered;	
				var rCounties     = jsonObject.Resources[a].Counties;
				
				if (rURL != '') {
					rURL = '<a href="'+rURL+'" title="Visit website">'+rURL+'</a>';
				}
				if (rEmail != '') {
					rEmail = '<a href="mailto:'+rEmail+'" title="Email Provider">'+rEmail+'</a>';
				}
				
				if ((a % 2) > 0) { 
					rowClass = 'altRow'; 
				} else { 
					rowClass = '';
				}
				stringOut += '<tr class="'+rowClass+'" id="'+rID+'">';
				stringOut += '<td></td>';
				stringOut += '<td>'+rName+'</td>';
				stringOut += '<td>';
				stringOut += rURL+'<br />'+rEmail;
				stringOut += '</td>';
				stringOut += '<td>'+rCounties+'</td>';
				stringOut += '<td>'+rDateEntered+'</td>';
				stringOut += '</tr>';
			} 
			stringOut += '</table>';			
		} else {
			stringOut = '<p>There are no resource providers in this category yet.</p>';
		}
		$('resourceList').innerHTML = stringOut;
	},
	renderFileCategories : function (stringJSON) {
		var jsonObject = stringJSON.evalJSON();
		var totalItems = (jsonObject.Categories.length)-1;
		var siteArea   = jsonObject.SiteArea;
		var catType    = jsonObject.CatType;
		var mainCatID  = jsonObject.MainID;
		var categoryContainer = $('resourceFileCategoryList');
		var subCategoryContainer = $('categoryWindow'+mainCatID);
		var noOfFiles;
		
		/*
		 * Clear subCategoryContainer if it exists
		 */
		if (subCategoryContainer) {
			$(subCategoryContainer).innerHTML = '';
		}
		if (catType == 'MainCat') {
			var categoryHeading = document.createElement('h1');
			categoryHeading.innerHTML = siteArea+'s';
			categoryContainer.appendChild(categoryHeading);
		}	
		
		for(var a=0;a<=totalItems;a++) {
			var catTitle  = jsonObject.Categories[a].CatTitle;
			var catID     = jsonObject.Categories[a].CatID;
			var noOfFiles = jsonObject.Categories[a].NoOfFiles;
			
			if (catType == 'MainCat') {	
				/*
				 * File main-categories
				 */
				if (noOfFiles == 1) {
					var fileText = 'file';
				} else {
					var fileText = 'files';
				}
			
				var categoryDiv = document.createElement('div');
				var catString = '<div class="emphBox"><div class="emphBoxInner">';
				catString    += '<div onClick="resourcesGetObj.toggleCategoryWindow(\'categoryWindow'+catID+'\','+catID+',\''+siteArea+'\'); return false;" title="Click to view files" style="cursor: pointer; float: left;">';
				catString    += '<span class="arrowDown" id="mainCatHeading'+catID+'" style="margin-bottom: 0px;">'+catTitle+'</span> <span id="noOfFiles'+catID+'">['+noOfFiles+' '+fileText+']</span>';
				catString    += '</div><div style="float: right;">';
				catString    += '</div><div style="clear: both;"></div></div></div>';
				catString    += '<div id="categoryWindow'+catID+'" style="display: none;"><div id="scriptaculousNeedsMe">';
				catString    += '</div></div><div style="height: 10px;"></div>';
				
				categoryDiv.innerHTML = catString;
				categoryContainer.appendChild(categoryDiv);
			} else {
				/*
				 * File sub-categories
				 */
				if (noOfFiles == 1) {
					var fileText = 'file';
				} else {
					var fileText = 'files';
				}
				
				var categoryDiv = document.createElement('div');
				var catString = '<div class="header2" style="padding-left: 12px;">';
					catString    += '<div onClick="resourcesGetObj.toggleCategoryWindow(\'categoryWindow'+catID+'\','+catID+',\''+siteArea+'\'); return false;" title="Click to view files" style="cursor: pointer; float: left;">';
					catString    += '<span class="arrowDown" id="mainCatHeading'+catID+'" style="margin-bottom: 0px; font-weight: bold;">'+catTitle+'</span> <span style="font-weight: bold;" id="noOfFiles'+catID+'">['+noOfFiles+' '+fileText+']</span>';
				catString    += '</div><div style="float: right;">';
				catString    += '</div><div style="clear: both;"></div></div>';
				catString    += '<div id="categoryWindow'+catID+'" style="display: none;"><div id="scriptaculousNeedsMe">';
				catString    += '</div></div><div style="height: 10px;"></div>';
				
				categoryDiv.innerHTML = catString;
				subCategoryContainer.appendChild(categoryDiv);
			}
		}
		
	},
	toggleCategoryWindow : function(categoryContainer,catID,siteArea) {
		var categoryWindow = $(categoryContainer);
		if (categoryWindow.style.display == '') {
			$('mainCatHeading'+catID).className = 'arrowDown';
			new Effect.SlideUp(categoryWindow, {direction: 'top', duration: .3});
		} else {
			/*
			 * Switch arrow position
			 */
			$('mainCatHeading'+catID).className = 'arrowUp';
			this.getFileCategories(siteArea,catID);
			new Effect.SlideDown(categoryWindow, {direction: 'top', duration: .3});
		}
	},
	getResourceFiles : function(catID) {
		var params = 'handler=getResourceFilesByCategory&catID='+catID;
		var ajaxResults = new Ajax.Request('ajaxDirector.php', {
			method: 'POST',
			parameters: params,
			onSuccess: function(transport) {
				resourcesGetObj.renderResourceFiles(transport.responseText);
			},
			onFailure: function() {
				alert('Oops!');
			}	
		});		
	},
	renderResourceFiles : function(stringJSON) {
		var jsonObject = stringJSON.evalJSON();
		var totalItems = (jsonObject.Files.length)-1;
		var userLevel  = jsonObject.Level;
		
		var itemRenderString = '<table class="dataTable" style="font-size: 1em;">';	
		itemRenderString += '<tr>';
		if (userLevel == 1) {
			itemRenderString += '<th style="width: 5%;"></th>';
		}	
		itemRenderString += '<th style="width: 25%;">File Title</th>';
		itemRenderString += '<th style="width: 50%;">Description</th>';
		itemRenderString += '<th style="width: 10%;">Date</th>';
		itemRenderString += '<th style="width: 10%;">Size</th>';
		itemRenderString += '</tr>';
		
		for (i = 0; i <= totalItems; i++) {
			if ((i % 2) > 0) { 
				rowClass = 'altRow'; 
			} else { 
				rowClass = '';
			}
			var fileID       = jsonObject.Files[i].FID;
			var catID        = jsonObject.Files[i].CatID;
			var fileTitle    = jsonObject.Files[i].FileTitle;
			var fileDesc     = jsonObject.Files[i].FileDesc;
			var fileSize     = jsonObject.Files[i].FileSize;
			var filePath     = jsonObject.Files[i].FilePath;
			var fileName     = jsonObject.Files[i].FileName;
			var mimeIconClass= jsonObject.Files[i].MimeIconClass;
			var convFileSize = jsonObject.Files[i].ConvFileSize;
			var dateAdded    = jsonObject.Files[i].DateUpdate;
			var dateFormat   = jsonObject.Files[i].FileDateFormat;
			
			itemRenderString += '<tr id="fileRow'+fileID+'" class="'+rowClass+'">';
			if (userLevel == 1) {
				itemRenderString += '<td style="text-align: center;" id="cellAction'+fileID+'">';
				itemRenderString += '<a href="#" onClick="trashUpdateObj.sendToTrash('+fileID+',\'file\'); return false;" title="Delete this file"><img src="images/buttonDeleteBig.gif" style="border: none;" alt="Delete this file" /></a>&nbsp;';
				itemRenderString += '<a href="#" onClick="resourcesUpdateObj.getFileInfoForEdit('+fileID+'); return false;" title="Edit this entry"><img src="images/buttonEditBig.gif" style="border: none;" alt="Edit this entry" /></a>';
				itemRenderString += '</td>';
			}	
			itemRenderString += '<td id="fileTitle'+fileID+'">';
			itemRenderString += '<div id="fileTitleContainer'+fileID+'" class="'+mimeIconClass+'"><a href="'+filePath+'" ext:qtip="'+fileName+' '+convFileSize+'">'+fileTitle+'</a></div>';
			itemRenderString += '<div id="fileTitleEditContainer'+fileID+'"></div>';
			itemRenderString += '</td>';
			itemRenderString += '<td id="fileDesc'+fileID+'"><div id="fileDescContainer'+fileID+'">'+fileDesc+'</div>';
			itemRenderString += '<div id="fileDescEditContainer'+fileID+'"></div></td>';
			itemRenderString += '<td>'+dateFormat+'</td>';
			itemRenderString += '<td style="text-align: right;">'+convFileSize+'</td>';
			itemRenderString += '</tr>';			
		}	
		itemRenderString += '</table>';
		$('categoryWindow'+catID).innerHTML = itemRenderString;		
	}
}

var resourcesUpdateObj = {
	returnDeleteFile : function(fileID) {
		Effect.Fade('fileRow'+fileID, {delay: .1, duration: 1});
	},
	convertRowToEditForm : function(fileID) {
		var origTitle = $('fileTitleContainer'+fileID).innerHTML;
		var origDesc  = $('fileDescContainer'+fileID).innerHTML
		
		var fileDescContent = '<textarea style="width: 100%;" id="fileDescField'+fileID+'">'+origDesc+'</textarea>';
		fileDescContent    += '<div style="margin-top: 10px; margin-left: 5px;">';
		fileDescContent    += '<div style="float: left; margin-right: 5px;"><a href="#" class="coolButton buttonBGBlueGray" tabindex="30" onClick="resourcesUpdateObj.editFile('+fileID+'); return false;"><span class="save">Save</span></a></div>';
		fileDescContent    += '<div style="float: left;"><a href="#" class="coolButton buttonBGRed" tabindex="30" onClick="resourcesSupportObj.closeEditForm('+fileID+'); return false;"><span class="cancel">Cancel</span></a></div>';
		fileDescContent    += '<div style="clear: left;"></div></div>';
		
		$('fileTitleEditContainer'+fileID).innerHTML = '<input type="text" style="width: 100%;" id="fileTitleField'+fileID+'" value="'+origTitle+'" />';
		$('fileDescEditContainer'+fileID).innerHTML  = fileDescContent;
		
		$('fileTitleContainer'+fileID).style.display = 'none';
		$('fileDescContainer'+fileID).style.display = 'none';
	},
	getFileInfoForEdit : function(fileID) {
		/*
		 * Reload file form with file data
		 */
		$('fileFrame').src = 'uploadFile.php?fID='+fileID;
		/*
		 * Open file form window
		 */
		resourcesSupportObj.openAddEditForm('edit');
		
	},
	editFile : function(fileID) {
		
	},
	saveResource : function() {
		var countyArray = $$('.countyList');
		var countyString = '';
		for(a=0;a<=((countyArray.length)-1);a++) {
			var county = countyArray[a].innerHTML;
			countyString += county+'|';
		}
		
		var dataString = {
				action:         $F('formAction'),
				resourceID:     $F('resourceID'),
				counties:       countyString,
				rType:          $F('rType'),
				rName:          $F('rName'),
				rDescription:   $F('rDescription'),
				rURL:           $F('rURL'),
				rContact:       $F('rContactPerson'),
				rServiceArea:   $F('rServiceArea'),
				rAddress:       $F('rAddress'),
				rCity:          $F('rCity'),
				rState:         $F('rState'),
				rZip:           $F('rZip'),
				rPhone:         $F('rPhone'),
				rFax:           $F('rFax'),
				rEmail:         $F('rEmail'),
				rNotes:         $F('rNotes')				
		};		
		jsonString = Object.toJSON(dataString);
		
		var params = 'handler=saveResource&jsonString='+jsonString;
		var ajaxResults = new Ajax.Request('ajaxDirector.php', {
			method: 'POST',
			parameters: params,
			onSuccess: function(transport) {
				var response = transport.responseText;
				var responseArray = response.split('|');
				var resourceID = responseArray[0];
				var rType      = responseArray[1];
				updateStatus('Resource has been saved.','success','messageSaveResource');
				resourcesGetObj.getResources(rType);
			},
			onFailure: function(response) {					
				logErrorAJAX(response);
			}
		});
	}
}

var viewTabContent = {
	content0Load : function() {
		
	},
	content1Load : function() {
		/*
		 * Get file categories
		 */
		resourcesGetObj.getFileCategories('Resource File');
		resourcesGetObj.getFileCategories('Shared Resource File');
	}
}
